<script setup>
import Toast from '@vant/weapp/dist/toast/toast';
import newLoading from '@/components/newLoading/index.vue';
import { getCategoryDetail } from '@/api/home'
import { convertPhotoV2, editImgUpload, getImageByTaskId } from '@/api/painting';


import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 页面携带参数
const queryItem = ref({})

// 查询详情信息
const queryInfo = ref({})

// 页面参数
const queryParams = ref({
    imageFileUrl: '',
})

// 提交数据
const queryData = ref({
    ifColor: 1,// 是否上色 0不上色只增强亮度， 1强制上色， 2智能上色
})

// 消耗算力
const expendNum = ref(0)

const loading = ref(false);
const loadingRef = ref(null)

// 任务id
const taskId = ref('')
// 定时器
let timer = null


// 立即生成
async function createFn() {
    await verifyFn()
    loading.value = true
    await editImgUploadFn()
    convertPhotoV2Fn()
}


// 校验方法
function verifyFn() {
    return new Promise((resolve, reject) => {
        if (!queryParams.value.imageFileUrl) {
            Toast.fail('请上传图片')
            return reject()
        }
        resolve()
    })
}





// 获取任务状态
async function getImageByTaskIdFn() {
    const res = await getImageByTaskId(taskId.value)
    if (res.data.state === 1) {
        clearInterval(timer);
        await loadingRef.value.completeLoading()
        res.data.title = queryInfo.value.title
        uni.navigateTo({
            url: `/newEditionDraw/recreationDrawResult/index?data=${JSON.stringify(res.data)}`
        })
    } else if (![3, 4].includes(res.data.state)) {
        clearInterval(timer);
        Toast.fail("绘图失败！");
        loading.value = false
    }
}



// 老照片修复任务提交
async function convertPhotoV2Fn() {
    try {
        const res = await convertPhotoV2(queryData.value)
        taskId.value = res.data.taskId
        timer = setInterval(() => {
            getImageByTaskIdFn()
        }, 2000)
    } catch (error) {
        loading.value = false
    }
}




// 上传原图
async function editImgUploadFn() {
    return new Promise(async (resolve, reject) => {
        try {
            const res = await editImgUpload({
                type: 23,
                orgImg: queryParams.value.imageFileUrl
            })
            queryData.value.imageFileUrl = res
            resolve()
        } catch (error) {
            loading.value = false
            reject()
        }
    })
}



// 图片预览
function previewImageFn() {
    uni.previewImage({
        urls: [queryParams.value.imageFileUrl],
    });
}


// 相册选择
function uploadImgFn() {
    uni.chooseImage({
        count: 1,
        success: (res) => {
            queryParams.value.imageFileUrl = res.tempFilePaths[0]
        }
    })

}



// 获取分类详情
async function getCategoryDetailFn() {
    const res = await getCategoryDetail(queryItem.value.id)
    queryInfo.value = res.data
    dataConversion()
}




// 数据转换
function dataConversion() {
    queryInfo.value.categoryParam.forEach(item => {
        if (item.title === 'expendNum') {
            expendNum.value = item.data[0].title
        }
    })
}


// 加载关闭事件
function loadingClose() {
    clearInterval(timer);
}


onLoad((e) => {
    if (e.item) {
        queryItem.value = JSON.parse(e.item)
    }
    getCategoryDetailFn()
})
</script>

<template>
    <div class='oldPhotoRestoration'>
        <NavBar>老照片修复</NavBar>
        <div class="container">
            <div class="img_box">
                <!--上传按钮-->
                <div v-if="!queryParams.imageFileUrl" class="uploadImgBtn" @click="uploadImgFn">
                    <i class="iconfont ai-icon-xiangcexuanze"></i>
                    相册选择
                </div>
                <!--重新上传-->
                <div v-else class="uploadBox" @click="uploadImgFn">
                    <i class="iconfont ai-icon-shangchuan"></i>
                    <p class="anewUpload">上传</p>
                </div>

                <img v-if="queryParams.imageFileUrl" :src="queryParams.imageFileUrl" alt="" class="imgSty" mode="aspectFit"
                    @click="previewImageFn">
            </div>
        </div>

        <div class="footer">
            <div class="footer_placeholder"></div>
            <div class="footer_content">
                <div class="create_btn" @click="createFn">
                    <div class="create_btn_title">一键修复</div>
                    <div class="create_btn_label">消耗:{{ expendNum }}算力</div>
                </div>
            </div>
        </div>
    </div>
    <van-toast id="van-toast" />
    <newLoading ref="loadingRef" v-model="loading" :duration="10000" :label="['排队中，预计等待大于15秒钟']" @close="loadingClose">
    </newLoading>
</template>

<style lang='scss' scoped>
.oldPhotoRestoration {
    height: 100vh;
    display: flex;
    flex-direction: column;

    .container {
        box-sizing: border-box;
        flex: 1;
        padding: 30rpx;
        display: flex;
        flex-direction: column;

        .img_box {
            flex: 1;
            border-radius: 20rpx;
            background-color: var(--a-main-box-bg-color);
            position: relative;

            .uploadImgBtn {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: 228rpx;
                height: 84rpx;
                border-radius: 45rpx;
                background-color: transparent;
                border: 3rpx solid var(--a-main-color);
                color: var(--a-one-text-color);
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 10rpx;
            }

            .uploadBox {
                position: absolute;
                bottom: 20rpx;
                right: 20rpx;
                color: var(--a-one-text-color);
                width: 88rpx;
                height: 88rpx;
                background-color: #fff;
                background: rgba(0, 0, 0, 0.65);
                border-radius: 50%;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;

                .iconfont {
                    font-size: 42rpx;
                }

                .anewUpload {
                    font-size: 22rpx;
                }
            }

            .imgSty {
                width: 100%;
                height: 100%;
            }
        }
    }

    .footer {
        .footer_placeholder {
            height: 176rpx;
        }

        .footer_content {
            box-sizing: border-box;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 176rpx;
            background: #212142;
            padding: 28rpx 30rpx 0;

            .create_btn {
                height: 86rpx;
                background: #83CD88;
                border-radius: 44rpx;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;

                .create_btn_title {
                    font-size: 32rpx;
                    color: #FFFFFF;
                }

                .create_btn_label {
                    font-size: 20rpx;
                    color: #FFFFFF;
                }
            }
        }
    }
}
</style>